/*
 * Copyright 2013 s.randoll.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.client.infrastructure.rest;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import de.digiway.rapidbreeze.client.model.download.DownloadResourceRepository;
import de.digiway.rapidbreeze.shared.rest.ResourceLocation;
import de.digiway.rapidbreeze.shared.rest.download.DownloadResource;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.Validate;

/**
 * A {@linkplain DownloadResourceRepository} implementation based on a rest
 * client which connects to a restful Rapid Breeze Server instance.
 *
 * @author s.randoll
 */
public class DownloadResourceRepositoryRestClient implements DownloadResourceRepository {

    private Client client;
    private String host;
    private String username;
    private String password;
    private int port;

    public DownloadResourceRepositoryRestClient(String host, int port, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
        this.client = Client.create();
    }

    @Override
    public boolean hasDownload(String identifier) {
        Validate.notEmpty(identifier, "There must be a valid identifier provided.");

        try {
            URI uri = getUri(ResourceLocation.DOWNLOAD_RESOURCE_PATH, identifier);
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).get(ClientResponse.class);
            return response.getStatus() == ClientResponse.Status.OK.getStatusCode();
        } catch (URISyntaxException ex) {
            return false;
        }
    }

    @Override
    public DownloadResource getDownload(String identifier) {
        Validate.notEmpty(identifier, "There must be a valid identifier provided.");

        try {
            URI uri = getUri(ResourceLocation.DOWNLOAD_RESOURCE_PATH, identifier);
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).get(ClientResponse.class);
            if (response.getStatus() == ClientResponse.Status.OK.getStatusCode()) {
                return response.getEntity(DownloadResource.class);
            } else if (response.getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) {
                throw new IllegalArgumentException("Cannot find download with identifier:" + identifier);
            } else {
                throw new IllegalArgumentException("An exceptional error occured in the restful repository: " + response.getEntity(String.class));
            }
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Cannot handle download url.", ex);
        }
    }

    @Override
    public List<DownloadResource> getDownloads() {
        try {
            URI uri = getUri(ResourceLocation.DOWNLOAD_RESOURCE_PATH);
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).get(ClientResponse.class);
            if (response.getStatus() == ClientResponse.Status.OK.getStatusCode()) {
                GenericType<List<DownloadResource>> type = new GenericType<List<DownloadResource>>() {
                };
                return response.getEntity(type);
            } else {
                throw new IllegalArgumentException("An exceptional error occured in the restful repository: " + response.getEntity(String.class));
            }
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Cannot handle download url.", ex);
        }
    }

    @Override
    public boolean canHandleUrl(String url) {
        try {
            URI uri = getUri(ResourceLocation.URL_INFORMATION_RESOURCE_PATH, URLEncoder.encode(url));
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).head();
            return response.getStatus() == ClientResponse.Status.OK.getStatusCode();
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Cannot handle download url.", ex);
        }
    }

    @Override
    public DownloadResource addDownload(String url) {
        Validate.notEmpty(url, "Cannot add an empty url.");

        try {
            URI uri = getUri(ResourceLocation.DOWNLOAD_RESOURCE_PATH);
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).post(ClientResponse.class, url);
            if (response.getStatus() == ClientResponse.Status.CREATED.getStatusCode()) {
                return response.getEntity(DownloadResource.class);
            } else if (response.getStatus() == ClientResponse.Status.BAD_REQUEST.getStatusCode()) {
                throw new IllegalArgumentException("Cannot handle given URL: " + url + ". " + response.getEntity(String.class));
            } else {
                throw new IllegalArgumentException("An exceptional error occured in the restful repository: " + response.getEntity(String.class));
            }
        } catch (URISyntaxException ex) {
            throw new IllegalArgumentException("Cannot handle given URL: " + url + ".", ex);
        }
    }

    @Override
    public void removeDownload(DownloadResource resource) {
        Validate.notNull(resource, DownloadResource.class.getSimpleName() + " must not be null.");

        try {
            URI uri = getUri(ResourceLocation.DOWNLOAD_RESOURCE_PATH, resource.getIdentifier());
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).delete(ClientResponse.class);

            if (response.getStatus() == ClientResponse.Status.OK.getStatusCode()) {
            } else if (response.getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) {
                throw new IllegalArgumentException("Cannot find resource to remove: " + resource);
            } else {
                throw new IllegalStateException("An error in the restful resource repository occured:" + response.getEntity(String.class) + ". Cannot update resource:" + resource);
            }
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Internal system error. Cannot parse uri.", ex);
        }
    }

    @Override
    public DownloadResource updateDownload(DownloadResource resource) {
        Validate.notNull(resource, DownloadResource.class.getSimpleName() + " must not be null.");

        try {
            URI uri = getUri(ResourceLocation.DOWNLOAD_RESOURCE_PATH + "/" + resource.getIdentifier());
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).put(ClientResponse.class, resource);
            if (response.getStatus() == ClientResponse.Status.OK.getStatusCode()) {
                return getDownload(resource.getIdentifier());
            } else if (response.getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) {
                throw new IllegalArgumentException("Cannot find resource to update: " + resource);
            } else {
                throw new IllegalStateException("An error in the restful resource repository occured:" + response.getEntity(String.class) + ". Cannot update resource:" + resource);
            }
        } catch (URISyntaxException ex) {
            throw new IllegalStateException("Internal system error. Cannot parse uri.", ex);
        }
    }

    private URI getUri(String... paths) throws URISyntaxException {
        UriBuilder builder = UriBuilder.fromPath("http://" + host + ":" + port);
        for (String path : paths) {
            builder.path(path);
        }
        return builder.build();
    }
}
